package drrr.orm;

import drrr.common.SpringContext;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

/**
 * The Service for Dao
 * Created by Xun on 2015/4/18.
 */
public abstract class Service {
    private AllDao allDao;

    public AllDao getAllDao() {
        return allDao;
    }

    public void setAllDao(AllDao allDao) {
        this.allDao = allDao;
    }

    /**
     * 执行Select查询语句
     * @param sql
     * @return 所有的数据项
     */
    public static List query(String sql)
    {
        Session session = SpringContext.getOpenedSession();
        Transaction tx = session.beginTransaction();
        try {
            return session.createSQLQuery(sql).list();
        }finally {
            tx.commit();
            session.close();
        }
    }

    /**
     * 返回查询的第一行数据
     * @param sql Select查询语句
     * @return 查询的第一行数据
     */
    public static List queryScalar(String sql)
    {
        Session session = SpringContext.getOpenedSession();
        Transaction tx = session.beginTransaction();
        try{
            return (List)session.createSQLQuery(sql).list().get(0);
        }catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }finally {
            tx.commit();
            session.close();
        }
    }

    /**
     * 执行update，delete,create等sql语句
     * @param sql sql语句(update，delete,create)
     * @return 影响的行数
     */
    public static int execute(String sql)
    {
        Session session = SpringContext.getOpenedSession();
        Transaction tx = session.beginTransaction();
        try{
            return  session.createSQLQuery(sql).executeUpdate();
        }catch (Exception e)
        {
            e.printStackTrace();
            return 0;
        }finally {
            tx.commit();
            session.close();
        }
    }

    //Find All of the data of Entity
    public abstract List<Entity> getAllEntities();

    //Add the entityRef To the database by the Dao
    public abstract void insert(Entity entityRef);
}
